package dotdashdot.bradz.trendsettr;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ActivitySetTrend extends Activity{
	
	//final String[] trend_list = new String[]{"Justin Bieber","Miley Cyrus","George Clooney","Apples","Duct Tape","Russia","Freedom",
	//		"Puppies","Gravity","Comcast","Barack Obama","Mardi Gras","New Years","Shrimp Toast","Screwdrivers"};
	
	private Context self;
	private ClassGestureListener gesture_listener;
	private OnTouchListener touch_listener;
	private ClassTrendingContainer trend_container;
	//private Random random = new Random(System.nanoTime());
	private int topic_index;
	private int trend_index;
	private int decision_threshold;
	private int screen_width;
	private ClassFonts fonts;
	//private Bundle extras;
	private ClassNetworkHelper helper;
	private TextView trends_text;
	private ClassUserCredentials credentials;
	private LinearLayout trend_layout;
	private Handler handler = new Handler();
	//private Drawable popular_vote, unpopular_vote/*, yes_emphasis, no_emphasis*/;
	private TextView disclaimer_text, popular_text, unpopular_text, no_percent_text, yes_percent_text;
	private ApplicationGlobalVars globals;
	private SetTrendsRunnable trend_runnable;
	private static ClassUberLogger logger;
	
  	Handler myHandler = new Handler() {

  		boolean in_use = false;
  		
  	    @Override
  	    public void handleMessage(Message msg) {
  	        switch (msg.what) {
  	        case 0:
  	        	init_trends();
  	        	//On return we free up the var so we can refresh again
  	        	in_use = false;
  	            break;
  	        case 1:
  	        	//We need to make sure that the network is only refreshing once per load
  	        	if(!in_use){
  	        		in_use = true;
  	        		refresh_trend_list();
  	        	}
  	        	break;
  	        case 2:
  	        	//We need to make sure that the filter tab does something...
  	        	//realign_filters();
  	        	break;
  	        case 5:
	        	format_credentials();
	        	break;
  	        case 6:
  	        	handler.postDelayed(trend_runnable, 2500);
	        	break;
  	        default:
  	            break;
  	        }
  	    }
  	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_trend);
		
		logger = new ClassUberLogger("ActivitySetTrend");

		fonts = new ClassFonts(this.getAssets());
		disclaimer_text = (TextView) findViewById(R.id.disclaimer_text);
		popular_text = (TextView) findViewById(R.id.popular_text);
		unpopular_text = (TextView) findViewById(R.id.unpopular_text);
		no_percent_text = (TextView) findViewById(R.id.no_percent);
		yes_percent_text = (TextView) findViewById(R.id.yes_percent);

		//yes_emphasis = getResources().getDrawable(R.drawable.emphasis_green);
		//no_emphasis = getResources().getDrawable(R.drawable.emphasis_red);
		
		decision_threshold = 100;
		
		Display display = getWindowManager().getDefaultDisplay();
		screen_width = display.getWidth();
		
		globals = ((ApplicationGlobalVars) this.getApplication());
		helper = new ClassNetworkHelper(this,((ApplicationGlobalVars) this.getApplication()));
		credentials = new ClassUserCredentials(globals);
		
		//Network call here
		if(!credentials.logged_in){
			helper.apply_for_credentials(credentials, myHandler);
		}else{
			format_credentials();
		}
		
		trend_layout = (LinearLayout) findViewById(R.id.trend_layout_inner);
		trend_layout.setOnTouchListener(gesture_listener);
		self = this;
		format_nav_tab();

		logger.info("OnCreate finished");
	}
	
	public void refresh_trend_list(){
		trend_container = new ClassTrendingContainer();
		helper.get_all_from_network_set_trend(trend_container, myHandler);
		logger.info("Done refreshing trend list");
	}
	
    @Override
    public void onResume(){
    	super.onResume();
    	if(!credentials.logged_in && !helper.applying()){
			helper.apply_for_credentials(credentials, myHandler);
		}else if(!helper.applying()){
			format_credentials();
		}
    	logger.info("OnResume finished");
    }
    
	@Override
    public boolean dispatchTouchEvent(MotionEvent ev){
		//TODO: This needs to be uncommented if we want to put swipes back in
		
		//gesture_listener.getGestureDetector().onTouchEvent(ev);
		
		//TODO: This needs to be uncommented if we want to put the touch listener back in
		
		logger.info("Enabling sticky touch gestures...");
		gesture_listener.onTouch(trend_layout, ev);
        
		return super.dispatchTouchEvent(ev);   
    }
	
	private void init_trends(){
		new load_filter_popup_task().execute();
	}
	
	private void format_nav_tab(){
		disclaimer_text.setTypeface(fonts.get_font("bold"));
		
		popular_text.setTypeface(fonts.get_font("medium_italic"));
		unpopular_text.setTypeface(fonts.get_font("medium_italic"));
		
		no_percent_text.setTypeface(fonts.get_font("cond_bold"));
		yes_percent_text.setTypeface(fonts.get_font("cond_bold"));
		
		final Button navigation_text = (Button) findViewById(R.id.top_navigation_button);
		navigation_text.setTypeface(fonts.get_font("cond_medium"));
		
		trends_text = (TextView) findViewById(R.id.trend_text);
		trends_text.setTypeface(fonts.get_font("cond_medium"));
		trends_text.setText("Loading Trends...");
		logger.info("Navtab formatted");
	}
	
	private static class SetTrendsRunnable implements Runnable {
		 private final Context self;
	     private final ClassTrendingContainer unanswered_trends;
	     //private final LinearLayout trend_layout;
	     private final FrameLayout background_yes, background_no;
	     private final TextView disclaimer_text, trends_text, popular_text, unpopular_text, no_percent_text, yes_percent_text;
	     private final ImageView yes_trend, no_trend;
	     private int topic_index;
		 private int trend_index;
		 private int local_vote;
	     private Random random = new Random(System.nanoTime());
	     private boolean thinking;

	     SetTrendsRunnable(final Context self, final ClassTrendingContainer unanswered_trends, 
	    		 /*final LinearLayout trend_layout,*/ final TextView disclaimer_text, 
	    		 final TextView trends_text, final TextView popular_text, final TextView unpopular_text,
	    		 final TextView yes_percent_text, final TextView no_percent_text, final ImageView yes_trend, final ImageView no_trend,
	    		 FrameLayout background_yes, FrameLayout background_no) {
	       this.unanswered_trends = unanswered_trends;
	       //this.trend_layout = trend_layout;
	       this.self = self;
	       this.disclaimer_text = disclaimer_text;
	       this.trends_text = trends_text;
	       this.trend_index = -1;
	       this.topic_index = -1;
	       this.local_vote = -1;
	       this.popular_text = popular_text;
	       this.unpopular_text = unpopular_text;
	       this.yes_percent_text = yes_percent_text;
	       this.no_percent_text = no_percent_text;
	       this.yes_trend = yes_trend;
	       this.no_trend = no_trend;
	       this.background_yes = background_yes;
	       this.background_no = background_no;
	       thinking = false;
	       set_text();
	     }

	     public void set_local_vote(final int local_vote){
	    	 this.local_vote = local_vote;
	     }
	     
	     public void set_thinking(){
	    	 thinking = true;
	     }
	     
	     public boolean get_thinking(){
	    	 return thinking;
	     }
	     
	     public void run() {
	    	   thinking = false;
	    	   //trend_layout.setBackgroundColor(self.getResources().getColor(R.color.transparent));
	    	   
	    	   background_no.setVisibility(View.INVISIBLE);
	    	   background_yes.setVisibility(View.INVISIBLE);
	    	   
			   disclaimer_text.setVisibility(View.VISIBLE);
			   popular_text.setVisibility(View.INVISIBLE);
			   unpopular_text.setVisibility(View.INVISIBLE);
			   yes_percent_text.setVisibility(View.INVISIBLE);
			   no_percent_text.setVisibility(View.INVISIBLE);
			   
			   yes_trend.setAlpha(1f);
	           no_trend.setAlpha(1f);
			   
			   unanswered_trends.set_trend_vote(topic_index,trend_index,local_vote);
		       set_text();
		       swipes_remaining();
		       logger.info("Resetting set trend UI...");
	     }
	     
	     public boolean swipes_remaining(){
	    	boolean remaining = topic_index!=-1 && trend_index!=-1;
	    	if(!remaining){
	    		logger.info("No more trends to swipe for!");
	    		disclaimer_text.setVisibility(View.INVISIBLE);
	    	}
	 		return remaining;
	 	}
	     
	     private void set_text(){
	 		if(unanswered_trends.get_topic_list().size()>0){
	 			topic_index = random.nextInt(unanswered_trends.get_topic_list().size());
	 			trend_index = random.nextInt(unanswered_trends.get_topic_list().get(topic_index).get_trend().size());
	 			String title = unanswered_trends.get_topic_list().get(topic_index).get_name();
	 			String text = unanswered_trends.get_topic_list().get(topic_index).get_trend().get(trend_index).get_name();
	 			logger.info("Setting trend text...");
	 			logger.info("Title: " + title);
	 			logger.info("Title index: "+topic_index);
	 			logger.info("Trend text: " + text);
	 			logger.info("Trend index: "+trend_index);
	 			logger.info("Done setting trend text...");
	 			trends_text.setText(text);
	 		}else{
	 			topic_index=-1;
	 			trend_index=-1;
	 			//trends_title.setText("No new trends");
	 			trends_text.setText("Out Of Trends");
	 			logger.info("Out of trends");
	 		}
	 	}
	  }
	
	public String format_trend(String trend){
		//This did something before, but not anymore
		//The final formatting before the trend hits the network parsing
		return trend;
	}
	
	private void init_touch_listener(){

		logger.info("Init Touch Listener");
		final ClassTrendingContainer unanswered_trends = trend_container.get_unseen_list(new ArrayList<String>(), true);
		
		//This is just a pointer to the various change elements for the async gesture listener...
		trend_runnable = new SetTrendsRunnable(this, unanswered_trends, /*trend_layout,*/ disclaimer_text, trends_text, 
				popular_text, unpopular_text, yes_percent_text, no_percent_text, 
				(ImageView) findViewById(R.id.trend_yes), (ImageView) findViewById(R.id.trend_no),
				(FrameLayout) findViewById(R.id.yes_frame),  (FrameLayout) findViewById(R.id.no_frame));
		
		final ClassTrendResultContainer result_container = 
				new ClassTrendResultContainer(yes_percent_text, no_percent_text, disclaimer_text, trend_layout,popular_text, unpopular_text, 
						(FrameLayout) findViewById(R.id.yes_frame),  (FrameLayout) findViewById(R.id.no_frame));

		gesture_listener = new ClassGestureListener(self) {
			int last_offset = 0;
			boolean swipe_valid = false;
			
			//String topic;
		    public void onSwipeTop() {
		        //Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
		    }
		    public void onSwipeRight() {
		    	logger.info("Swipe Right");
		    	if(trend_runnable.swipes_remaining() && !trend_runnable.get_thinking()){
		    		//This all depends on the values returned from the server
		    		
		    		findViewById(R.id.trend_yes).setAlpha(1f);
		            findViewById(R.id.trend_no).setAlpha(0.2f);
		    		
		    		result_container.voted_for(true);
		    		
			    	logger.info("Saving: " + unanswered_trends.get_topic_list().get(trend_runnable.topic_index).get_trend().get(trend_runnable.trend_index).get_name());
		    		//The helper needs to be returned 
			    	ArrayList<NameValuePair> post_data = new ArrayList<NameValuePair>();
			    	post_data.add(new BasicNameValuePair("trendName", unanswered_trends.get_topic_list().get(trend_runnable.topic_index).get_trend().get(trend_runnable.trend_index).get_name()));
		    		helper.post_network(post_data, "/vote",result_container,myHandler);

		    		trend_runnable.set_local_vote(1);
		    		trend_runnable.set_thinking();
		    	}
		    }
		    public void onSwipeLeft() {
		    	logger.info("Swipe Left");
		    	if(trend_runnable.swipes_remaining() && !trend_runnable.get_thinking()){
		    		
		    		findViewById(R.id.trend_yes).setAlpha(0.2f);
		            findViewById(R.id.trend_no).setAlpha(1f);
		    		 
		    		result_container.voted_for(false);
		    		
			    	logger.info("Saving: " + unanswered_trends.get_topic_list().get(trend_runnable.topic_index).get_trend().get(trend_runnable.trend_index).get_name());
		    		
			    	ArrayList<NameValuePair> post_data = new ArrayList<NameValuePair>();
			    	post_data.add(new BasicNameValuePair("trendName", unanswered_trends.get_topic_list().get(trend_runnable.topic_index).get_trend().get(trend_runnable.trend_index).get_name()));
		    		helper.post_network(post_data, "/downvote",result_container,myHandler);
		    		
		    		trend_runnable.set_local_vote(-1);
		    		trend_runnable.set_thinking();
		    	}
		    }
		    public void onSwipeBottom() {
		        //Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
		    }
			    
		    public void onDown(float x_offset){
		    	//This is just here to make sure that the swipe is valid before the trend is moved
		    	int down_offset = (int) Math.abs(x_offset);
		    	//logger.info("Swipe Down Offset: " + down_offset);
		    	if(down_offset > screen_width/4 && down_offset< 3*screen_width/4){
		    		swipe_valid = true;
		    	}else{
		    		swipe_valid = false;
		    	}
		    }
		    
		    public void onMove(float x_offset){
		    	if(swipe_valid){
			    	if(trend_runnable.swipes_remaining()){
				    	if(last_offset > screen_width/2){
					    	//logger.info("Move Right: " + Math.abs(x_offset));
				    		//int threshold = 7*screen_width/10;
				    		int padding = (int) Math.abs(x_offset) - screen_width/2/* > threshold ? threshold : (int) Math.abs(x_offset) - screen_width/2*/;
				    		
				    		trends_text.setPadding(padding, 0, 0, 0);
				    	}else{
					    	//logger.info("Move Left: " + Math.abs(x_offset));
				    		
				    		//int threshold = 3*screen_width/10;
				    		int padding = (int) screen_width/2 - (int) Math.abs(x_offset)/* < threshold ? threshold : (int) screen_width/2 - (int) Math.abs(x_offset)*/;
				    		
				    		trends_text.setPadding(0, 0, padding, 0);
				    	}
			            
				    	//right
				    	if(last_offset > 3*screen_width/4){
				            
				            /*ImageView yes_percent_image = (ImageView) findViewById(R.id.trend_yes);
				            ImageView no_percent_image = (ImageView) findViewById(R.id.trend_no);
				            yes_percent_image.setBackgroundDrawable(yes_emphasis);
				            no_percent_image.setBackgroundColor(self.getResources().getColor(R.color.transparent));*/
				    		
				    		findViewById(R.id.trend_yes).setAlpha(1f);
				            findViewById(R.id.trend_no).setAlpha(0.2f);
				            
				            //yes_things.setBackgroundColor(self.getResources().getColor(R.color.list_green));
				            //no_things.setBackgroundColor(self.getResources().getColor(R.color.transparent));
				            
				    	//left
				    	}else if(last_offset < screen_width/4){
				            
				            /*ImageView yes_percent_image = (ImageView) findViewById(R.id.trend_yes);
				            ImageView no_percent_image = (ImageView) findViewById(R.id.trend_no);
				            no_percent_image.setBackgroundDrawable(no_emphasis);
				            yes_percent_image.setBackgroundColor(self.getResources().getColor(R.color.transparent));*/
				            
				            //trend_layout_no_things
				    		
				    		findViewById(R.id.trend_yes).setAlpha(0.2f);
				            findViewById(R.id.trend_no).setAlpha(1f);
				            
				            //yes_things.setBackgroundColor(self.getResources().getColor(R.color.transparent));
				            //no_things.setBackgroundColor(self.getResources().getColor(R.color.list_red));
				    	}else{
				    		findViewById(R.id.trend_yes).setAlpha(1f);
				            findViewById(R.id.trend_no).setAlpha(1f);
				            //yes_things.setBackgroundColor(self.getResources().getColor(R.color.transparent));
				            //no_things.setBackgroundColor(self.getResources().getColor(R.color.transparent));
				    	}
				    	last_offset = (int) Math.abs(x_offset);
		    		}
		    	}
		    }
		    public void notMoving(){
		    	if(trend_runnable.swipes_remaining()){
			    	//logger.info("Trend not moving anymore...");
			    	
			    	trends_text.setPadding(0, 0, 0, 0);
			    	
			    	/*ImageView yes_percent_image = (ImageView) findViewById(R.id.trend_yes);
		            ImageView no_percent_image = (ImageView) findViewById(R.id.trend_no);
		            yes_percent_image.setBackgroundColor(self.getResources().getColor(R.color.transparent));
		            no_percent_image.setBackgroundColor(self.getResources().getColor(R.color.transparent));   */
		            
		            //findViewById(R.id.trend_layout_no_things).setBackgroundColor(self.getResources().getColor(R.color.transparent));
		            //findViewById(R.id.trend_layout_yes_things).setBackgroundColor(self.getResources().getColor(R.color.transparent));
		            
		            //findViewById(R.id.trend_yes).setAlpha(1f);
		            //findViewById(R.id.trend_no).setAlpha(1f);
		            
			    	if(last_offset > 3*screen_width/4){
				    	//logger.info("Yes Vote!");
			    		onSwipeRight();
			    	}else if(last_offset < screen_width/4){
				    	//logger.info("No Vote!");
			    		onSwipeLeft();
			    	}
		    	}
		    }
		};
	}

	private void format_credentials(){
		TextView user_name_text_view = (TextView) this.findViewById(R.id.user_name_footer);
    	TextView user_rank_text_view = (TextView) this.findViewById(R.id.user_rank_footer);
    	user_name_text_view.setTypeface(fonts.get_font("medium_italic"));
    	user_rank_text_view.setTypeface(fonts.get_font("medium"));
    	user_name_text_view.setText(credentials.name);
    	user_rank_text_view.setText("Trendsettr Rank: "+credentials.rank);
    	globals.set_credentials_store(credentials);
		if(myHandler != null){
			myHandler.sendEmptyMessage(1);
		}
    	logger.info("Credentials loaded");
    }
	
	//Make sure that the network is active and working...
  	private class load_filter_popup_task extends AsyncTask<Void, Void, Void> {
  		ArrayList<String> topic_list;

  		@Override
        protected void onPreExecute() {
  			topic_list = new ArrayList<String>();
  	        for(ClassTopic topic:trend_container.get_topic_list()){
  	        	topic_list.add(topic.get_name());
  	        }
  		}
  		
  		@Override
  		protected Void doInBackground(Void... arg0) {
  			//info_popup = new ClassFilterPopup(self,fonts,topic_list,myHandler);
  			return null;
  		}
  		
  		@Override
  	    protected void onPostExecute(Void v) {
  			//info_popup.attach_popup_window((View)findViewById(R.id.top_navigation_button),getWindowManager().getDefaultDisplay());
  			init_touch_listener();
  		}
  	}
}
